Optional Heap.f

Requires Stacks

{
Because of how simple it is, this scheme is very fast, but its tradeoff is that it isn't very memory-efficient.
If you allocate a lot of stuff and then discard it, that memory will be free only for new blocks that fit the
same allocation size.
This version's maximum allocation size is 1K.
}

: stock  ( max size "name" -- ) create swap 0 , dup , swap , stack, \ max, size, stored, [stack]
   does>
      1 over +!
      @+ swap @+ swap >r  > abort" Error: Out of chunks of that size - increase stock size."
      r> @+ swap dup empty? if cell- cell- , here swap  /allot
         else pop dup rot erase then ;

20000 20 stock 20's
20000 100 stock 100's
20000 256 stock 256's
20000 512 stock 512's
20000 1024 stock 1k's

: recycle  ( a-)
   dup cell- @ 0< abort" Error: Program tried to free a static object!"
   dup cell- @ cell+ cell+ push ;

: chunk   ( n-a) locals| n |
   n 20 <= if 20's exit then
   n 100 <= if 100's exit then
   n 256 <= if 256's exit then
   n 512 <= if 512's exit then
   n 1024 <= if 1k's exit then
   -1 abort" Error: Couldn't allocate a chunk. The requested size was too big." ;
